<template>
  <div class="geoPositionWrap classMain">
    <NavBar
      :title="'网格实况'"
      :text="'返回'"
      :cityName="cityName"
      :areaName="areaName"
      @clicksPopul="clicksPopul"
    ></NavBar>
    <div id="mapgeo" style="width: 100%; height: 100%"></div>
    <!--要素点击-->

    <div class="tuceng" @click="tucengclick">
      <img
        style="width: 25px; height: 25px"
        src="../../assets/liveData/tuceng.png"
        alt=""
      />
      图层
    </div>
    <Sidebar :arr="arr" @changeFactor="changeFactor"></Sidebar>
    <!-- 温度 -->
    <TemperatureControl
      :factorIndex="factorIndex"
      style="position: relative; bottom: -25px"
    ></TemperatureControl>
    <positioning @bindEvent="bindEvent" :possinon="possinon"></positioning>
    <popup
      v-if="showpopul == true"
      @close="showpopul = false"
      @huanhu="huanhu"
    ></popup>
    <comArea
      v-if="showArea"
      @closeEmit="showArea = false"
      :arr="arr1"
      @confirmEmit="confirmEmitMet"
    >
    </comArea>
    <canvas id="canvasMap" style="display: none"></canvas>
  </div>
</template>
<script type="text/javascript">
import meteoroLiveDataApi from "@/service/liveData.js";
import TransformationApi from "@/service/power.js";
import forecastimg from "../../assets/icon/leidianicon.png";
import forecastimgd from "../../assets/icon/d.png";
import forecastimgji from "../../assets/icon/jianhao1.png";
import popup from "../../components/popup/index.vue";
import comArea from "../../components/common/area.vue";

import Sidebar from "../common/Sidebar.vue";
import Vue from "vue";
import { Popup } from "vant";
import map from "@/util/map.js";
import { getItem, setItem } from "../../util/storage.js";
Vue.use(Popup);
export default {
  data() {
    return {
      factorIndex: 0,
      showArea: false,
      geo: null,
      ldshow: false,
      forecastimgji: forecastimgji,
      forecastimg: forecastimg,
      possinon: true,
      index: 0,
      thunder: {},
      styles: "aegis://styles/aegis/Streets-v2",
      cityName: "",
      activetuceng: "",
      showpopul: false,
      popupDOM: null,
      mapgeo: null,
      show: true,
      arr1: [],
      path: "ws://121.52.212.68:9092/websocket/1",
      //   path: 'ws:192.168.1.35:9092/websocket/1',
      socket: "",
      type: "温度",

      lei: false,
      longAndLati: {
        lapsXcoordinate: "",
        lapsYcoordinate: "",
      },
      areaName: "",
      elMarker: "",
      popupItem: {},
      leiDian: [],
      market: [],
      map: null,
      marketHistory: [],
      cityName: "",
      leiD: "",
      arr: [
        {
          text: "温度",
          unactive: "wendu.png",
          active: "wenduActive.png",
        },
        {
          text: "湿度",
          unactive: "shi.png",
          active: "shiActive.png",
        },
        {
          text: "风速",
          unactive: "feng.png",
          active: "fengActive.png",
        },
        {
          text: "降水",
          unactive: "rain.png",
          active: "rainActive.png",
        },
        {
          text: "雷电",
          unactive: "lei.png",
          active: "leiActive.png",
        },
      ],
    };
  },
  created() {
    this.areaName = this.$store.getters.location[2].name;
    map.init().then((res) => {
      //当前定位的城市
      
      var location = getItem("location");
      if (location.length > 0) {
        this.cityName = location[1].name;
      }

      //初始化经纬度
      this.longAndLati.lapsXcoordinate = this.$store.getters.cityLongAndLati[0];
      this.longAndLati.lapsYcoordinate = this.$store.getters.cityLongAndLati[1];
      // this.info_getTime()

      this.$util.bianKong();
      this.initMap([
        this.longAndLati.lapsXcoordinate,
        this.longAndLati.lapsYcoordinate,
      ]);
    });
  },

  destroyed: function () {
    map.remove();
    // 离开页面生命周期函数
    // this.websocketclose()
  },

  computed: {
    cityLongAndLati() {
      return this.$store.getters.cityLongAndLati;
    },
  },

  watch: {},
  components: {
    popup,
    Sidebar,
    comArea,
  },
  methods: {
    init1: function () {
      if (typeof WebSocket === "undefined") {
        alert("您的浏览器不支持socket");
      } else {
        // 实例化socket
        this.socket = new WebSocket(this.path);
        // 监听socket连接
        this.socket.onopen = this.open;
        // 监听socket错误信息
        this.socket.onerror = this.error;
        // 监听socket消息
        this.socket.onmessage = this.getMessage;
      }
    },
    open: function () {
      console.log("连接成功");
    },
    error: function () {
      console.log("连接错误");
    },
    getMessage: function (msg) {
      var msg = JSON.parse(msg.data);

      this.Marker(msg);
      this.Markerhistory(msg);
    },

    // 发送消息给被连接的服务端
    send: function (params) {
      this.socket.send(params);
    },
    close: function () {
      console.log("socket已经关闭");
    },
    huanhu(style) {
      map.setBaseStyle(style);
    },
    Marker(msg) {
      var _this = this;
      if (msg.msgTxt.length == 0) {
        return;
      }
      msg.msgTxt.forEach((it) => {
        var el = document.createElement("div");
        el.style.background = `url("${forecastimg}") no-repeat`;
        el.style.width = "25px";
        el.style.height = "25px";
        el.style.backgroundSize = "cover";
        el.setAttribute("data-name", JSON.stringify(it));
        // if (_this.selecttext !== '最大风速') {
        var elMarker = new SGMap.Marker({
          element: el,
          anchor: "bottom",
          //   rotation: 45,
        })
          .setLngLat([it.lon, it.lat])
          .addTo(_this.map);
        // _this.market.push(elMarker)
        el.addEventListener("click", function (e) {
          var log1 = JSON.parse(e.target.getAttribute("data-name"));

          _this.showPopupDOM(_this.map, log1.lon, log1.lat, log1);
        });
      });
    },
    Markerhistory(msg) {
      if (msg.history.length == 0) {
        return;
      }
      var _this = this;
      msg.history.forEach((it) => {
        var el = document.createElement("div");
        el.style.background = `url("${forecastimgd}") no-repeat`;
        el.style.width = "25px";
        el.style.height = "25px";
        el.style.backgroundSize = "cover";
        el.setAttribute("data-name", JSON.stringify(it));
        // if (_this.selecttext !== '最大风速') {
        var elMarker = new SGMap.Marker({
          element: el,
          anchor: "bottom",
          //   rotation: 45,
        })
          .setLngLat([it.lon, it.lat])
          .addTo(_this.map);
        // _this.marketHistory.push(elMarker)
        el.addEventListener("click", function (e) {
          var log1 = JSON.parse(e.target.getAttribute("data-name"));

          _this.showPopupDOM(_this.map, log1.lon, log1.lat, log1);
        });
      });
    },
    clearMarket() {
      if (this.market.length != 0) {
        this.market.forEach((it) => {
          it.remove();
        });
      }
      if (this.marketHistory.length != 0) {
        this.marketHistory.forEach((it) => {
          it.remove();
        });
      }
    },
    tucengclick() {
      this.showpopul = true;
    },
    confirmEmitMet(value) {
      var _this = this;
      _this.showArea = false;
      _this.$util.Convertlatitude(value).then((result) => {
        _this.longAndLati.lapsXcoordinate = result[0];
        _this.longAndLati.lapsYcoordinate = result[1];
        var location = [result[0], result[1]];
       
        _this.cityName = value[1].name;
        _this.areaName = value[2].name;
        _this.arr1 = [value[1].name, value[2].name];

        //设置中心点
        _this.map.setCenter(location);
        _this.initLiveDataApi();
      });
    },
    onClickLeft() {
      this.$router.go(-1);
    },
    clicksPopul() {
      this.showArea = true;
   
      this.arr1 = [this.cityName, this.areaName];
    },

    loadPlugin() {
      var _that = this;
      SGMap.plugin("SGMap.GeolocationTask").then(function (res) {
        _that.initMap();
      });
    },
    initMap(location, style, remove) {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });
      var _this = this;

      _this.map = new SGMap.Map({
        // 地图绑定的DOM元素ID
        container: "mapgeo",
        // 地图样式
        style: "aegis://styles/aegis/Streets-v2",
        // 默认缩放层级
        zoom: 11,
        // 地图中心点
        center: location,
        // 地图默认字体
        localIdeographFontFamily: "Microsoft YoHei",
      });

      _this.map.on("load", function (e) {
        _this.$util.initLayerAll("", _this.map);
        _this.$util.searchAll("", _this.map);
        // _this.map.addControl(new SGMap.GeolocateControl(), "bottom-left");
        _this.initLiveDataApi();
        //渲染
        _this.getInit("温度");
      });

      this.popupDOM = new SGMap.Popup({
        // info_geo
        closeButton: true,
        closeOnClick: false,
        offset: {
          bottom: [0, 0],
        },
      });
      _this.map.on("click", function (e) {
        _this.longAndLati.lapsXcoordinate = e.lngLat.lng;
        _this.longAndLati.lapsYcoordinate = e.lngLat.lat;
        if (_this.factorIndex != 4) {
          _this.initLiveDataApi();
        }
        _this.possinon = true;
      });
    },

    //渲染
    getInit(type) {
      var _this = this;
      _this.$toast.loading({
        message: "渲染中...",
        forbidClick: true,
        duration: 0,
      });
      var params = {
        type: type,
      };

      meteoroLiveDataApi.Liverendering(params).then((res) => {
        _this.features = res.features;
        _this.$toast.clear();

        _this.$util.canvans(_this.features, _this.factorIndex, _this.map);

        _this.showPopupDOM(
          _this.map,
          _this.longAndLati.lapsXcoordinate,
          _this.longAndLati.lapsYcoordinate,
          undefined
        );
        _this.$toast.clear();
      });
    },

    changeFactor(item, index) {
      this.factorIndex = index;

      this.type = item;
      if (index == 0) {
        this.close();
        this.leiD = item;
      } else if (index == 1) {
        this.close();
        this.leiD = item;
      } else if (index == 2) {
        this.close();

        this.leiD = item;
      } else if (index == 3) {
        this.close();

        this.leiD = item;
      } else if (index == 4) {
        this.factorIndex = -1;
        this.popupDOM.remove();
        this.$util.allclearcanvans(this.map);
        this.map.setBaseStyle("aegis://styles/aegis/StreetsDark");
        // 初始化
        this.init1();
        this.leiD = "雷电";
        return;
      }
      // map.setBaseStyle("aegis://styles/aegis/Streets-v2");

      this.info_getTime(this.type);
    },

    info_getTime(type) {
      var _this = this;

      var params = {
        type,
      };

      meteoroLiveDataApi.info_geo(params).then((res) => {
        _this.features = res.features;

        if (_this.leiD != "雷电") {
          _this.$util.allclearcanvans(_this.map);
        }

        _this.getInit(type);

        _this.showPopupDOM(
          _this.map,
          _this.longAndLati.lapsXcoordinate,
          _this.longAndLati.lapsYcoordinate,
          undefined
        );
        // }
      });
    },
    showPopupDOM(map, lng, lat, text) {
      this.popupDOM.remove();
      this.popupDOM
        .setLngLat([lng, lat])
        .setHTML(this.popUpHtml(text))
        .addTo(map);
    },
    popUpHtml(text) {
      console.log(text);
      if (text != undefined) {
        let htmlStr = `
            <div style="padding:6px;">
<div>   陡度：${text.dd}  </div>

<div>  高度:${text.gd}  </div>
<div>  类型: ${text.lx == 0 ? "正极" : "负极"}   </div>
<div> 峰值强度 : ${text.qd > 0 ? "正" : "负"}   </div>
<div> 误差 : ${text.wc}   </div>

                </div>
           `;

        return htmlStr;
      } else {
        let type = this.type;
        var dongtiatype = "";
        if (type == "温度") {
          dongtiatype = parseInt(this.popupItem.temp) + "℃";
        } else if (type == "湿度") {
          type = "相对湿度";
          dongtiatype = parseInt(this.popupItem.rrh) + "%rh";
        } else if (type == "风速") {
          type = "风速/风向";
          dongtiatype = `${parseInt(this.popupItem.speed)}m/s/${parseInt(
            this.popupItem.direction
          )}°`;
        } else {
          type = "雨量";
          dongtiatype = parseInt(this.popupItem.rain) + "mm";
        }

        let htmlStr = `
            <div style="padding:6px;">

                <div class='popHtmlLi'    style="text-align: left;" ><span>${type}:${dongtiatype}</div>



                </div>
           `;
        return htmlStr;
      }
    },
    initLiveDataApi() {
      var _this = this;

      TransformationApi.shikong({
        lat: this.longAndLati.lapsYcoordinate,
        lon: this.longAndLati.lapsXcoordinate,
      })
        .then((res) => {
          console.log(res);

          _this.popupItem = res.t;
          _this.showPopupDOM(
            _this.map,
            _this.longAndLati.lapsXcoordinate,
            _this.longAndLati.lapsYcoordinate
          );
        })
        .catch((err) => {
          _this.popupItem = err.t;
          _this.showPopupDOM(
            _this.map,
            _this.longAndLati.lapsXcoordinate,
            _this.longAndLati.lapsYcoordinate
          );
        });
    },
    bindEvent() {
      var _that = this;
      SGMap.plugin("SGMap.GeolocationTask").then(function (res) {
        var geo = new SGMap.GeolocationTask();
        geo
          .getLocation()
          .then(function (data) {
            var arr1 = data[0].map(Number);

            _that.map.setCenter(arr1);
            _that.longAndLati.lapsYcoordinate = arr1[1];
            _that.longAndLati.lapsXcoordinate = arr1[0];
            _that.initLiveDataApi();
            //设置缩放
            _that.$toast("定位成功");
            _that.possinon = false;
          })
          .catch(function (e) {
              _that.$toast('定位失败')
            _that.possinon = true;
          });
      });

      // 手动定位
    },
  },
  destroyed() {
    // 销毁监听
    this.close();
  },
};
</script>
<style type="text/css" lang="less" scoped>
.geoPositionWrap {
  overflow: hidden;
  position: relative;
  width: 100%;
  height: 100%;
}
.tuceng {
  position: absolute;
  width: 40px;
  display: flex;
  z-index: 99;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 12px;
  padding: 4px;
  height: 40px;
  right: 15px;
  top: 23%;
  background: #ffffff;
  box-shadow: 0px 0px 15px 0px rgba(222, 222, 222, 0.36);
  border-radius: 5px;
}
/deep/ .sgmap-popup-close-button {
  top: 0 !important;
  width: 15px !important;
  height: 15px !important;
  background: transparent !important;
  border-radius: 50% !important;
  display: flex !important;
  justify-content: center !important;
  align-items: center !important;

  z-index: 99999 !important;
  color: transparent !important;
  font-size: 16px !important;
}

.rights {
  color: #fff;
}
/deep/ .van-nav-bar__content {
  background: #357cff;
}

/deep/ .van-button--normal {
  padding: 0 10px;
  font-size: 14px;
  height: 25px;
  margin-left: 3px;
}

.typeLineNew {
  right: 15px;
}
</style>
